package com.whut.welcomepage.fragment;

/**
 * Created by Noone on 2016/9/3.
 * Today is today!
 */
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnHelper {
    public static byte[] getByteArrayFromNet(String urlString) {
        if (urlString != null) {
            BufferedInputStream bis = null;
            ByteArrayOutputStream baos = null;
            try {
                //创建url对象
                URL url = new URL(urlString);
                //创建HttpURLConnection对象
                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                httpConn.setRequestMethod("GET");
                httpConn.setConnectTimeout(5000);
                httpConn.setDoInput(true);
                httpConn.connect();
                // 判断跟服务器的连接状态。如果是200，则说明连接正常，服务器有响应
                if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    bis = new BufferedInputStream(httpConn.getInputStream());
                    baos = new ByteArrayOutputStream();
                    byte[] bytes = new byte[1024 * 8];
                    int len = 0;
                    while ((len = bis.read(bytes)) != -1) {
                        baos.write(bytes, 0, len);
                        baos.flush();
                    }
                    return baos.toByteArray();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    //对流对象进行关闭，以便释放资源
                    if (bis != null) {
                        bis.close();
                    }
                    if (baos != null) {
                        baos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        return null;
    }
}

